package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.entity.TaskEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
@Topic(TopicConfig.VMS_STATUS_TOPIC)
public class VmStatusHandler implements MsgHandler {

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskService taskService;

    @Override
    public void process(String jsonMsg) throws IOException {
        //反序列化
        VmStatusContract vmStatusContract = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
        if (vmStatusContract == null || vmStatusContract.getStatusInfo() == null || vmStatusContract.getStatusInfo().size() <= 0)
            return;
        //如果售货机为非正常状态，创建维修工单
        if (vmStatusContract.getStatusInfo().stream().anyMatch(s -> s.isStatus() == false)) {

            try {
                //查询售货机信息
                var vmInfo = vmService.getVMInfo(vmStatusContract.getInnerCode());
                //查询接单最少的运维人员
                var userId = taskService.getLeastUser(vmInfo.getRegionId(), true);

                var taskViewModel = new TaskViewModel();
                //自动创建
                taskViewModel.setCreateType(0);
                //设备编号
                taskViewModel.setInnerCode(vmStatusContract.getInnerCode());
                //执行人id
                taskViewModel.setUserId(userId);
                //工单类型
                taskViewModel.setProductType(VMSystem.TASK_TYPE_REPAIR);
                //描述信息
                taskViewModel.setDesc("自动维修工单");

                //创建工单
                taskService.create(taskViewModel);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("自动维修工单创建失败，msg is" + jsonMsg);
            }
        }
    }
}
